package com.kk.base.controller.home;

import com.kk.base.bean.CodeMsg;
import com.kk.base.bean.Result;
import com.kk.base.constant.SessionConstant;
import com.kk.base.entity.home.HomeUser;
import com.kk.base.entity.home.HomeUserIdCard;
import com.kk.base.service.home.HomeUserIdCardService;
import com.kk.base.service.home.HomeUserService;
import com.kk.base.util.SessionUtil;
import com.kk.base.util.StringUtil;
import com.kk.base.util.ValidateEntityUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @info : 前台用户个人中心控制层
 */
@RequestMapping("/home/userManager")
@Controller
public class HomeUserManagerController {


    @Autowired
    private HomeUserService homeUserService;
    @Autowired
    private HomeUserIdCardService homeUserIdCardService;

    /**
     * 跳转到个人中心首页
     * @param model
     * @return
     */
    @RequestMapping("/index")
    public String index(Model model) {
        HomeUser homeUser = SessionUtil.getHomeUser();
        model.addAttribute("homeUser", homeUser);
        model.addAttribute("index", 4);
        model.addAttribute("active", 0);
        return "home/user_manager/index";
    }


    /**
     * 修改个人信息
     * @param homeUser
     * @return
     */
    @RequestMapping("/update")
    @ResponseBody
    public Result<Boolean> update(HomeUser homeUser) {
        CodeMsg validate = ValidateEntityUtil.validate(homeUser);
        if (validate.getCode() != CodeMsg.SUCCESS.getCode()) {
            return Result.error(validate);
        }
        if (homeUserService.isExistMobile(homeUser.getName(), homeUser.getId())) {
            return Result.error(CodeMsg.HOMEUSER_MOBILE_EXIST);
        }
        HomeUser findById = homeUserService.find(homeUser.getId());
        //讲提交的管理员信息指定字段复制到已存在的user对象中,该方法会覆盖新字段内容
        BeanUtils.copyProperties(homeUser, findById, "id", "createTime", "updateTime", "password", "email");
        HomeUser save = homeUserService.save(findById);
        if (save == null) {
            return Result.error(CodeMsg.HOMEUSER_EDIT_ERROR);
        }
        SessionUtil.set(SessionConstant.SESSION_HOME_USER_LOGIN_KEY, save);
        return Result.success(true);
    }


    /**
     * 跳转到修改密码页面
     * @param model
     * @return
     */
    @RequestMapping("/updatePassword")
    public String updatePassword(Model model) {
        HomeUser homeUser = SessionUtil.getHomeUser();
        model.addAttribute("homeUser", homeUser);
        model.addAttribute("index", 4);
        return "home/user_manager/update_password";
    }


    /**
     * 修改密码
     * @param homeUser
     * @param code
     * @return
     */
    @RequestMapping(value = "/updatePassword", method = RequestMethod.POST)
    @ResponseBody
    public Result<Boolean> updatePassword(HomeUser homeUser, @RequestParam("code") String code) {

        String checkPhone = "^1[3|4|5|7|8]\\d{9}$";
        Pattern r = Pattern.compile(checkPhone);
        Matcher m = r.matcher(homeUser.getMobile());
        if (!m.matches()) {
            return Result.error(CodeMsg.HOMEUSER_MOBILE_ERROR);
        }
        if (!StringUtil.emailFormat(homeUser.getEmail())) {
            return Result.error(CodeMsg.COMMON_EMAIL_FORMAET_ERROR);
        }
        if (code == null) {
            return Result.error(CodeMsg.HOMEUSER_CODE_ERROR);
        }
        if (code.length() != 4) {
            return Result.error(CodeMsg.HOMEUSER_CODE_LENGTH_ERROR);
        }
        Object attr = SessionUtil.get(SessionConstant.HOME_USER_UPDATE_PASSWORD_CODE);
        if (attr == null) {
            return Result.error(CodeMsg.CODE_NOT_EMPTY);
        }
        if (!code.equalsIgnoreCase(attr.toString())) {
            return Result.error(CodeMsg.CPACHA_ERROR);
        }
        //验证通过，更新密码
        HomeUser byId = homeUserService.findByMobile(homeUser.getMobile());
        byId.setPassword(homeUser.getPassword());
        if (homeUserService.save(byId) == null) {
            return Result.error(CodeMsg.HOMEUSER_FORGET_ERROR);
        }
        SessionUtil.set(SessionConstant.HOME_USER_UPDATE_PASSWORD_CODE, null);
        return Result.success(true);
    }


    /**
     * 跳转到实名认证页面
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/realName")
    public String realName(Model model) {
        HomeUser homeUser = SessionUtil.getHomeUser();
        HomeUserIdCard byHomeUserId = homeUserIdCardService.findByHomeUser_Id(homeUser.getId());
        model.addAttribute("homeUser", homeUser);
        model.addAttribute("byHomeUserId", byHomeUserId);
        model.addAttribute("index", 4);
        model.addAttribute("active", 2);
        return "home/user_manager/real_name";
    }

    /**
     * 用户进行实名认证
     * @param homeUserIdCard
     * @param code
     * @return
     */
    @RequestMapping(value = "/addRealName", method = RequestMethod.POST)
    @ResponseBody
    public Result<Boolean> addRealName(HomeUserIdCard homeUserIdCard, @RequestParam("code") String code) {
        HomeUser homeUser = SessionUtil.getHomeUser();
        HomeUserIdCard byHomeUser_id = homeUserIdCardService.findByHomeUser_Id(homeUser.getId());
        if (byHomeUser_id != null) {
            return Result.error(CodeMsg.HOMEUSERIDCARD_EXIST);
        }
        CodeMsg validate = ValidateEntityUtil.validate(homeUserIdCard);
        if (validate.getCode() != CodeMsg.SUCCESS.getCode()) {
            return Result.error(validate);
        }
        if (code == null) {
            return Result.error(CodeMsg.HOMEUSER_CODE_ERROR);
        }
        if (code.length() != 4) {
            return Result.error(CodeMsg.HOMEUSER_CODE_LENGTH_ERROR);
        }
        Object attr = SessionUtil.get(SessionConstant.HOME_USER_REAL_NAME_CODE);
        if (attr == null) {
            return Result.error(CodeMsg.CODE_NOT_EMPTY);
        }
        if (!code.equalsIgnoreCase(attr.toString())) {
            return Result.error(CodeMsg.CPACHA_ERROR);
        }
        homeUserIdCard.setHomeUser(homeUser);
        if (homeUserIdCardService.save(homeUserIdCard) == null) {
            return Result.error(CodeMsg.HOMEUSERIDCARD_ERROR);
        }
        SessionUtil.set(SessionConstant.HOME_USER_REAL_NAME_CODE, null);
        return Result.success(true);
    }


}
